package com.example.consumer;

import com.example.util.ConnectionUtils;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.DeliverCallback;

import java.io.IOException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class Receiver {

    private final static String QUEUE_NAME = "task-queue";

    public static void main(String[] args) throws IOException, TimeoutException {

        Connection connection = ConnectionUtils.openConnection("Receiver1");
//        Connection connection = ConnectionUtils.openConnection("Receiver2");
        Channel channel = connection.createChannel();

        channel.queueDeclare(QUEUE_NAME, true, false, false, null);
        // 设置每个消费者在同时只能处理一条消息，注意，channel.basicQos()只在手动ACK模式下才生效
        channel.basicQos(1);

        System.out.println(" [*] 等待消息。退出按CTRL+C");

        DeliverCallback deliverCallback = (consumerTag, delivery) -> {
            String message = new String(delivery.getBody(), "UTF-8");

            System.out.println(" [x] 收到 '" + message + "'");
            try {
                doWork(message);
            } finally {
                System.out.println(" [x] Done");
                channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false);
            }
        };
        channel.basicConsume(QUEUE_NAME, false, deliverCallback, (consumerTag) -> {
        });

    }

    public static void doWork(String message) {
        try {
            // 模拟耗时的业务逻辑
            TimeUnit.MILLISECONDS.sleep(400);
//            TimeUnit.MILLISECONDS.sleep(10);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
